<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Cck\ArticlesSystem\Http\Models\Category;
use Cck\ArticlesSystem\Http\Resources\CategoryResource;
use Cck\ArticlesSystem\Http\Requests\CategoryStoreRequest;
use Cck\ArticlesSystem\Http\Requests\CategoryUpdateRequest;

class CategoriesController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = (int)max($request->query('page_size', 15), 10);
        $page = (int)max($request->query('page', 1), 1);

        $categories = Category::query()
            ->with($this->getWith())
            ->when($request->query('parent_id', '') !== '', function ($q) use ($request) {
                $q->where('parent_id', $request->query('parent_id'));
            })
            ->when($request->has('show_in_menus'), function ($q) use ($request) {
                $q->where('show_in_menus', (boolean)$request->query('show_in_menus'));
            })
            ->when($request->get('is_page', '') !== '', function ($q) use ($request) {
                $q->where('page', (boolean)$request->query('is_page'));
            })
            ->latest('order')
            ->paginate($pageSize, ['*'], 'page', $page);

        return CategoryResource::collection($categories);
    }

    public function all()
    {
        return CategoryResource::collection(Category::all());
    }

    public function store(CategoryStoreRequest $request)
    {
        return new CategoryResource(
            Category::create($request->validated())
        );
    }

    public function update(Category $category, CategoryUpdateRequest $request)
    {
        $category->update($request->validated());

        return ['status' => true];
    }

    public function show(Category $category)
    {
        return new CategoryResource($category);
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (!is_array($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        $ids = array_filter(array_unique(array_map('intval', $ids)));

        if (!count($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        \DB::beginTransaction();

        $count = Category::query()->whereIn('id', $ids)->delete();

        if (count($ids) !== $count) {
            \DB::rollBack();

            return ['status' => false, 'message' => '删除失败'];
        }

        \DB::commit();

        return ['status' => true];
    }
}
